package com.asseco.mio.codex.controllers;

import com.asseco.mio.codex.GeoArea;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.*;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import org.appfuse.Constants;

@Controller
@RequestMapping("/geoAreaform*")
public class GeoAreaFormController extends BaseFormController {

    private GenericManager<GeoArea, String> geoAreaManager = null;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setGeoAreaManager(@Qualifier("geoAreaManager") GenericManager<GeoArea, String> geoAreaManager) {
        this.geoAreaManager = geoAreaManager;
    }

    public GeoAreaFormController() {
        setCancelView("redirect:geoAreas");
        setSuccessView("redirect:geoAreas");
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected GeoArea showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String userString = request.getRemoteUser();
        try {
            if (!request.isUserInRole(Constants.ADMIN_ROLE)) {
                throw new Exception("");
            }

        } catch (Exception e) {

            response.sendRedirect("/MIO/mainMenu");
        }
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "geoAreaform", "geoArea.show", geoAreaManager.get(id).getName(),
                    "", request.getRemoteHost(), new Date()));
            return geoAreaManager.get(id);
        }


        return new GeoArea();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(GeoArea geoArea, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }
        if (validator != null) { // validator is null during testing
            validator.validate(geoArea, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "geoAreaform";
            }
        }


        log.debug("entering 'onSubmit' method...");

        boolean isNew = (geoArea.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "geoAreaform", "geoArea.delete", geoArea.getName(),
                    "", request.getRemoteHost(), new Date()));

            geoAreaManager.remove(geoArea.getId());
            saveMessage(request, getText("geoArea.deleted", locale));

        } else {
            geoAreaManager.save(geoArea);
            String key = (isNew) ? "geoArea.added" : "geoArea.updated";
            saveMessage(request, getText(key, locale));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "geoAreaform", key, geoArea.getName(),
                    "", request.getRemoteHost(), new Date()));
            if (!isNew) {
                success = "redirect:geoAreaform?id=" + geoArea.getId();
            }
        }

        return success;
    }
}
